package com.ziyan.service;

import com.ziyan.dao.AppInfoDao;
import com.ziyan.dto.AppInfoDTO;
import com.ziyan.entity.AppInfoEntity;
import com.ziyan.error.ErrorCode;
import com.ziyan.error.UCException;
import com.ziyan.utils.EncryptTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * Created by ZMy on 2017/5/24.
 */
@Service
public class AppInfoService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private AppInfoDao appInfoDao;

    public boolean checkSign(AppInfoDTO dto) {
        AppInfoEntity info = appInfoDao.findByAppid(dto.getAppid());
        if (info == null) {
            throw new UCException(ErrorCode.already_short_url);
        }
        boolean check = checkMessageDigest(
                dto.getTimestamp(), dto.getAppid(), dto.getRan(), info.getSecret(), dto.getSign());
        if (!check) {
            log.error("invalid sign %s,%s ", dto.getSign());
            throw new UCException(ErrorCode.invalid_params);
        }
        return true;
    }

    private boolean checkMessageDigest(String timestamp, String appId,
                                       String ran, String secret, String sign) {
        String[] contents = {ran, appId, timestamp, secret};
        try {
            Arrays.sort(contents);
            String content = "";
            for (String str : contents) content += str;
            String mySign = EncryptTool.sha1(content);
            return StringUtils.equals(mySign, sign);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
